package com.autoagent.ai_live_master.scriptRecommendation.service.impl;

import com.autoagent.ai_live_master.common.utils.BeanConverter;
import com.autoagent.ai_live_master.scriptRecommendation.dto.EcommerceBenefitsDTO;
import com.autoagent.ai_live_master.scriptRecommendation.entity.EcommerceBenefits;
import com.autoagent.ai_live_master.scriptRecommendation.mapper.EcommerceBenefitsMapper;
import com.autoagent.ai_live_master.scriptRecommendation.service.EcommerceBenefitsService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 电商权益配置表 服务实现类
 * </p>
 *
 * @author TraeAI
 * @since 2024-07-26
 */
@Slf4j
@Service
public class EcommerceBenefitsServiceImpl extends ServiceImpl<EcommerceBenefitsMapper, EcommerceBenefits> implements EcommerceBenefitsService {



    @Override
    public List<EcommerceBenefitsDTO> getEcommerceBenefitsByUserId(Long userId) {
        log.info("开始查询用户电商权益列表 - 用户ID: {}", userId);
        try {
            LambdaQueryWrapper<EcommerceBenefits> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(EcommerceBenefits::getUserId, userId);
            List<EcommerceBenefits> ecommerceBenefitsList = this.list(queryWrapper);
            List<EcommerceBenefitsDTO> result = ecommerceBenefitsList.stream()
                    .map(ecommerceBenefits -> BeanConverter.convert(ecommerceBenefits, EcommerceBenefitsDTO.class))
                    .collect(Collectors.toList());
            log.info("查询用户电商权益列表成功 - 用户ID: {}, 结果数量: {}", userId, result.size());
            return result;
        } catch (Exception e) {
            log.error("查询用户电商权益列表失败 - 用户ID: {}, 错误信息: {}", userId, e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public Page<EcommerceBenefitsDTO> getPageByUserId(Long userId, Integer pageNum, Integer pageSize, String keyword) {
        log.info("分页获取用户的电商权益列表 - 用户ID: {}, 页码: {}, 每页大小: {}, 关键字: {}", userId, pageNum, pageSize, keyword);

        Page<EcommerceBenefits> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<EcommerceBenefits> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EcommerceBenefits::getUserId, userId);

        // 如果有关键字，添加benefitName字段的模糊匹配
        if (keyword != null && !keyword.trim().isEmpty()) {
            wrapper.like(EcommerceBenefits::getBenefitName, keyword.trim());
        }

        // 按创建时间倒序排列
        wrapper.orderByDesc(EcommerceBenefits::getCreatedAt);

        Page<EcommerceBenefits> entityPage = this.page(page, wrapper);

        // 转换为DTO分页对象
        Page<EcommerceBenefitsDTO> dtoPage = new Page<>();
        dtoPage.setTotal(entityPage.getTotal());
        dtoPage.setCurrent(entityPage.getCurrent());
        dtoPage.setSize(entityPage.getSize());
        dtoPage.setRecords(entityPage.getRecords().stream()
                .map(entity -> BeanConverter.convert(entity, EcommerceBenefitsDTO.class))
                .collect(Collectors.toList()));

        return dtoPage;
    }


    @Override
    public EcommerceBenefitsDTO createEcommerceBenefits(EcommerceBenefits ecommerceBenefits) {
        log.info("开始创建电商权益 - 用户ID: {}", ecommerceBenefits.getUserId());
        try {
            this.save(ecommerceBenefits);
            EcommerceBenefitsDTO result = BeanConverter.convert(ecommerceBenefits, EcommerceBenefitsDTO.class);
            log.info("创建电商权益成功 - ID: {}, 用户ID: {}", ecommerceBenefits.getId(), ecommerceBenefits.getUserId());
            return result;
        } catch (Exception e) {
            log.error("创建电商权益失败 - 用户ID: {}, 错误信息: {}", ecommerceBenefits.getUserId(), e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public EcommerceBenefitsDTO updateEcommerceBenefits(EcommerceBenefits ecommerceBenefits) {
        log.info("开始更新电商权益 - ID: {}, 用户ID: {}", ecommerceBenefits.getId(), ecommerceBenefits.getUserId());
        try {
            EcommerceBenefits existingEcommerceBenefits = this.getById(ecommerceBenefits.getId());
            if (existingEcommerceBenefits == null) {
                log.warn("更新电商权益失败 - 电商权益不存在, ID: {}", ecommerceBenefits.getId());
                return null; // Or throw an exception
            }
            this.updateById(ecommerceBenefits);
            EcommerceBenefitsDTO result = BeanConverter.convert(ecommerceBenefits, EcommerceBenefitsDTO.class);
            log.info("更新电商权益成功 - ID: {}, 用户ID: {}", ecommerceBenefits.getId(), ecommerceBenefits.getUserId());
            return result;
        } catch (Exception e) {
            log.error("更新电商权益失败 - ID: {}, 用户ID: {}, 错误信息: {}", 
                    ecommerceBenefits.getId(), ecommerceBenefits.getUserId(), e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public boolean deleteEcommerceBenefits(Integer id) {
        log.info("开始删除电商权益 - ID: {}", id);
        try {
            EcommerceBenefits existingEcommerceBenefits = this.getById(id);
            if (existingEcommerceBenefits == null) {
                log.warn("删除电商权益失败 - 电商权益不存在, ID: {}", id);
                return false;
            }
            boolean result = this.removeById(id);
            log.info("删除电商权益{} - ID: {}", result ? "成功" : "失败", id);
            return result;
        } catch (Exception e) {
            log.error("删除电商权益失败 - ID: {}, 错误信息: {}", id, e.getMessage(), e);
            throw e;
        }
    }
}